import type { AxiosResponse } from "axios";
import * as XLSX from "xlsx";

export async function readFromXlsx(callBack: (wb: XLSX.WorkBook) => {}) {
  const files = await showOpenFilePicker();
  const file = await files[0].getFile();

  const reader = new FileReader();
  reader.onload = async function (e: any) {
    const data = e.target.result;
    const wb = XLSX.read(data, { type: "binary" });
    callBack(wb);
  };
  reader.readAsBinaryString(file);
}

export async function addModels<T extends ModelType>(
  wb: XLSX.WorkBook,
  sheetName: string,
  model: T,
  addMany: (data: T[]) => Promise<AxiosResponse<T[], any>>,
  lineId: number | undefined
) {
  const ws = wb.Sheets[sheetName];
  const row = XLSX.utils.sheet_to_json(ws);

  const arr: T[] = [];
  for (const r of row) {
    const keys = Reflect.ownKeys(model);
    for (const key of keys) {
      const value = Reflect.get(r as any, key) || "";

      if (typeof Reflect.get(model, key) === "string") {
        Reflect.set(model, key, value.toString());
      } else if (typeof Reflect.get(model, key) === "number") {
        Reflect.set(model, key, parseFloat(value));
      } else {
        Reflect.set(model, key, value);
      }
    }

    if (lineId === undefined) {
      arr.push({ ...model });
    } else {
      arr.push({ ...model, lineId });
    }
  }
  await addMany(arr);
}
